<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/11/23 0023
 * Time: 9:34
 */

namespace app\index\model;


use think\Model;

class Score extends Model
{
    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";
    protected $updateTime = "update_entered";

    public static function init()
    {
        self::event("before_delete", function ($query){
            //var_dump($query->id);
            //判断是否有关联数据
            return true;
        });
    }

    /**
     * @param int $offset
     * @param int $limit
     * @param array $where
     * @return array
     */
    public function getList($offset = 0, $limit=10, $where = [])
    {
        return $this->alias('s')
            ->field("s.*, sc.name as school_name, cl.name as class_name, co.name as course_name, st.name as stu_name, sct.name as type_name")
            ->leftJoin('school sc', "sc.id=s.school_id")
            ->leftJoin('class cl', "cl.id=s.class_id")
            ->leftJoin('course co', "co.id=s.course_id")
            ->leftJoin('student st', "st.id=s.stu_id")
            ->leftJoin('score_type sct', "sct.id=s.score_id")
            ->where($where)
            ->limit($offset, $limit)
            ->order('id', 'desc')->select()->toArray();
    }

    /**
     * @return array
     */
    public function getScoreRank($limit = 15)
    {
        return $this->alias('s')
            ->field("s.*, sc.name as school_name, cl.name as class_name, co.name as course_name, st.name as stu_name, sct.name as type_name")
            ->leftJoin('school sc', "sc.id=s.school_id")
            ->leftJoin('class cl', "cl.id=s.class_id")
            ->leftJoin('course co', "co.id=s.course_id")
            ->leftJoin('student st', "st.id=s.stu_id")
            ->leftJoin('score_type sct', "sct.id=s.score_id")
            ->limit($limit)
            ->order('score', 'desc')->select()->toArray();
    }

    /**
     * @param array $where
     * @return $this
     */
    public function getListCount($where = [])
    {
        return $this->alias('s')->where($where)->count();
    }

    /**
     * @param $id
     * @return array
     */
    public function getOneById($id)
    {
        return $this->where("id", $id)->findOrEmpty()->toArray();
    }

    /**
     * @param $data
     * @return bool
     */
    public function add($data)
    {
        return $this->save($data);
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public function edit($id, $data)
    {
        return $this->save($data, [['id', '=', $id]]);
    }

    /**
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        return self::get($id)->delete();
    }
}